/*CopyRight 2015 By YXKJ Co., Ltd. All Rights Reserved.*/
package com.yx.system.component;

import org.eclipse.swt.graphics.Image;
import com.yx.system.ModelDataUtils;

/**
 * 通用标签提供器
 * 
 * @author zgq
 */
public class LabelProvider extends org.eclipse.jface.viewers.LabelProvider
		implements org.eclipse.jface.viewers.ITableLabelProvider {
	/** 要用以显示的属性名数组 */
	private String[] propertys;
	/** 内容类型 */
	private Class<?> elementType;

	/**
	 * 获取 propertys
	 * 
	 * @return propertys
	 */
	public String[] getPropertys() {
		return propertys;
	}

	/**
	 * 设置 propertys
	 * 
	 * @param propertys
	 */
	public void setPropertys(String[] propertys) {
		this.propertys = propertys;
	}

	/**
	 * 获取 elementType
	 * 
	 * @return elementType
	 */
	public Class<?> getElementType() {
		return elementType;
	}

	/**
	 * 设置 elementType
	 * 
	 * @param elementType
	 */
	public void setElementType(Class<?> elementType) {
		this.elementType = elementType;
	}

	/**
	 * 构造方法(如果要显示多个属性，按显示的顺序放入属性名)<br/>
	 * 如果类型是<code>Object[].class</code>则不用指明要显示的属性了
	 * 
	 * @param elementType
	 *            内容类型
	 * @param propertys
	 *            要用以显示的属性名
	 */
	public LabelProvider(Class<?> elementType, String... propertys) {
		this.setElementType(elementType);
		this.setPropertys(propertys);
	}

	@Override
	public String getText(Object element) {
		try {
			if (element.getClass() == this.getElementType()) {
				Object obj = ModelDataUtils.getObjByName(element,
						this.getPropertys()[0]);
				return obj == null ? "" : obj.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getText(element);
	}

	@Override
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	@Override
	public String getColumnText(Object element, int columnIndex) {
		try {
			if (this.getElementType() == Object[].class) {
				Object[] elements = (Object[]) element;
				Object obj = elements[columnIndex];
				return obj == null ? "" : obj.toString();
			}
			if (element.getClass() == this.getElementType()) {
				Object obj = ModelDataUtils.getObjByName(element,
						this.getPropertys()[columnIndex]);
				return obj == null ? "" : obj.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return element.toString();
	}
}